// pages/forum/forum.js
Page({
  data: {
    posts: [],
    page: 1,
    pageSize: 10,
    hasMore: true,
    backendUrl: 'http://127.0.0.1:88/api/user/'
  },

  onLoad() {
    this.loadPosts();
  },

  onPullDownRefresh() {
    this.setData({
      page: 1,
      posts: [],
      hasMore: true
    }, () => {
      this.loadPosts();
    });
  },

  onReachBottom() {
    if (this.data.hasMore) {
      this.loadPosts();
    }
  },

  loadPosts() {
    wx.showLoading({
      title: '加载中...'
    });

    wx.request({
      url: 'http://127.0.0.1:88/api/user/post.php',
      method: 'GET',
      data: {
        action: 'list',
        page: this.data.page,
        pageSize: this.data.pageSize
      },
      success: (res) => {
        if (res.data.status === 'success') {
          const newPosts = res.data.posts;
          newPosts.forEach(post => {
            if (post.avatar) {
              post.avatar = this.data.backendUrl + post.avatar;
            }
            if (post.image) {
              post.image = post.image;
            }
          });
          this.setData({
            posts: [...this.data.posts, ...newPosts],
            page: this.data.page + 1,
            hasMore: newPosts.length === this.data.pageSize
          });
        }
      },
      complete: () => {
        wx.hideLoading();
        wx.stopPullDownRefresh();
      }
    });
  },

  handleSearchInput(e) {
    const keyword = e.detail.value;
    if (keyword) {
      wx.request({
        url: 'http://127.0.0.1:88/api/user/post.php',
        method: 'GET',
        data: { 
          action: 'list',
          keyword 
        },
        success: (res) => {
          if (res.data.status === 'success') {
            const posts = res.data.posts;
            posts.forEach(post => {
              if (post.avatar) {
                post.avatar = this.data.backendUrl + post.avatar;
              }
              if (post.image) {
                post.image = this.data.backendUrl + post.image;
              }
            });
            this.setData({
              posts: posts
            });
          }
        }
      });
    } else {
      this.setData({
        page: 1,
        posts: []
      }, () => {
        this.loadPosts();
      });
    }
  },

  goToDetail(e) {
    const { id } = e.currentTarget.dataset;
    wx.navigateTo({
      url: `/pages/post-detail/post-detail?id=${id}`
    });
  },

  goToPostEdit() {
    wx.navigateTo({
      url: '/pages/post-edit/post-edit'
    });
  }
});
